<script setup lang="ts">
import PageLayout from '@/components/PageLayout.vue';
import HeaderText from '@/components/HeaderText.vue';
import FlexCard from '@/components/FlexCard.vue';
import LRMenu from '@/components/LRMenu.vue';
import SwitchDark from '@/components/SwitchDark.vue';
import MiddleLayout from '@/components/MiddleLayout.vue';
import { getEmptyChessBoard, getWinner, aiNextStep, type ChessItemNonNull } from '@/utils/chess';
import ChessView from './main-view/ChessView.vue';
import { computed, ref } from 'vue';
import { ElButton, ElDivider } from 'element-plus';
import ChessItemView from './main-view/chess-view/ChessItemView.vue';
const chessBoard = ref(getEmptyChessBoard());
const nextItem = ref<ChessItemNonNull>('O');
const winner = computed(() => getWinner(chessBoard.value));
const clear = () => {
  chessBoard.value = getEmptyChessBoard();
  nextItem.value = 'O';
};
const put = ([x, y]: [number, number]) => {
  if (winner.value) {
    return;
  }
  chessBoard.value[x][y] = nextItem.value;
  nextItem.value = nextItem.value === 'O' ? 'X' : 'O';
};
const aiStep = () => {
  if (winner.value) {
    return;
  }
  const { x, y } = aiNextStep(chessBoard.value, nextItem.value);
  put([x, y]);
};
</script>

<template>
  <PageLayout>
    <template #header>
      <LRMenu>
        <HeaderText>Tic Tac Toe</HeaderText>
        <template #end>
          <SwitchDark></SwitchDark>
        </template>
      </LRMenu>
    </template>
    <MiddleLayout>
      <FlexCard>
        <LRMenu>
          <span style="padding: 20px">{{ winner ? 'Winner' : 'Next' }}</span>
          <ChessItemView :content="winner ? winner.winner : nextItem"></ChessItemView>
          <template #end>
            <ElButton :type="'success'" @click="aiStep">AI</ElButton>
            <ElButton :type="'danger'" @click="clear">Clear</ElButton>
          </template>
        </LRMenu>
        <ElDivider></ElDivider>
        <ChessView
          :content="chessBoard"
          :next="winner ? undefined : nextItem"
          @put="put"
        ></ChessView>
      </FlexCard>
    </MiddleLayout>
  </PageLayout>
</template>
